﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NTrace.VSPackage
{
    public partial class NTraceSettingsControl : UserControl
    {
        public NTraceSettingsControl() : this(null)
        {
        }
        public NTraceSettingsControl(NTraceConfiguration configuration)
        {
            InitializeComponent();
            this.PopulateFlagComboBox();
            this.configurationSource.Add(configuration);
        }

        private void PopulateFlagComboBox()
        {
            DataGridViewComboBoxColumn column = (this.flags.Columns[0] as DataGridViewComboBoxColumn);
            for (int index = 0; index < 32; index++) column.Items.Add(index);
        }

        private void etwProviderId_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                Guid temp = new Guid(this.etwProviderId.Text);
                this.errorProvider.SetError(this.etwProviderId, null);
            }
            catch (FormatException)
            {
                this.errorProvider.SetError(this.etwProviderId, Strings.InvalidProviderId);
                e.Cancel = true;
            }
        }

        private void flags_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                e.Value = Convert.ToInt32(e.Value);
                e.ParsingApplied = true;
            }
        }

        private void flags_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                e.Cancel = true;
                int value;
                if (int.TryParse(e.FormattedValue as String, out value))
                {
                    int count = (this.configurationSource.Current as NTraceConfiguration).Flags.Count((i) => { return i.Flag == value; });
                    e.Cancel = count > 1;
                }
            }
            if (e.ColumnIndex == 2 && String.IsNullOrEmpty(e.FormattedValue as String)) e.Cancel = true;
        }
    }
}
